package com.feeyo.monitor.schedule;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.feeyo.monitor.utils.CoordTransform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.esri.core.geometry.OperatorDistance;
import com.esri.core.geometry.Point;
import com.feeyo.monitor.domain.VehicleHourlyArchiver;
import com.feeyo.monitor.service.VehicleHourlyArchiveService;
import com.feeyo.monitor.service.VehicleService;
import com.feeyo.monitor.service.VehicleTrackingService;
import com.feeyo.monitor.utils.DateUtils;

/**每小时生成车辆归档记录（每个整点的05分执行）
 * @Author <a href="mailto:bliulei@variflight.com">liulei</a>
 * @Description Created by liulei on 2017/5/15 下午6:02.
 */
@Component
public class ArchiverTaskImp implements ArchiverTask {
	Logger logger = LoggerFactory.getLogger(ArchiverTaskImp.class);
	@Autowired
	VehicleService vehicleService;
	@Autowired
	VehicleTrackingService vehicleTrackingService;
	@Autowired
	VehicleHourlyArchiveService vehicleHourlyArchiveService;
	private long timeInterval8h = 8*60*60*1000;
	@Scheduled(cron="0 5 */1 * * ?")
    //@Scheduled(initialDelay = 1000 * 5,fixedDelay = 1000 * 10)
	public void vehicleHourlyArchiver() {
		List<Map> vehicleList = vehicleService.selectAll();
		Date now = new Date();
		Date nowUtc = new Date(new Date().getTime() - timeInterval8h);
		String startTime = DateUtils.getHourlyStr(org.apache.commons.lang3.time.DateUtils.addHours(now, -1));
		String endTime = DateUtils.getHourlyStr(now);

        String startUtcTime = DateUtils.getHourlyStr(org.apache.commons.lang3.time.DateUtils.addHours(nowUtc, -1));
        String endUtcTime = DateUtils.getHourlyStr(nowUtc);

		logger.info("  start..."+startTime + "::::::" + endTime);

		for (Map vehicle : vehicleList){
			String vehicleId = (String)vehicle.get("id");
			List<List> trackingList = vehicleTrackingService.getTrackingByVehicle(vehicleId, startUtcTime, endUtcTime);

            if((trackingList ==null)||(trackingList.size() ==0))
				continue;
			double maxSpeed = 0;
			double sumSpeed = 0;
			double sumDistance = 0;
			int trackingCount = trackingList.size();
			for (int i=0; i<trackingCount; i++){
				double curLon = (double)trackingList.get(i).get(1);
				double curLat = (double)trackingList.get(i).get(2);
				double speed = (double)trackingList.get(i).get(3);
				if (curLat == 0 || curLon == 0)
				    continue;
				if (i != (trackingCount-1)){
					double nextLon = (double)trackingList.get(i+1).get(1);
					double nextLat = (double)trackingList.get(i+1).get(2);
//					Point curPoint = new Point(curLon, curLat);
//					Point nextPoint = new Point(nextLon, nextLat);

					double[] curCoord = CoordTransform.latlonToEPSG3857(curLat,curLon);
					double[] nextCoord = CoordTransform.latlonToEPSG3857(nextLat,nextLon);
                    Point curPoint = new Point(curCoord[1],curCoord[0]);
                    Point nextPoint = new Point(nextCoord[1],nextCoord[0]);

					double distance = OperatorDistance.local().execute(curPoint, nextPoint, null);
					sumDistance += distance;
				}
				if (speed > maxSpeed)
					maxSpeed = speed;
				sumSpeed += speed;
			}
			VehicleHourlyArchiver archiver = new VehicleHourlyArchiver();
			archiver.setVehicleid(vehicleId);
			archiver.setVehiclenumber((String)vehicle.get("number"));
			archiver.setMaxspeed(maxSpeed);
			archiver.setDistance(sumDistance);
			archiver.setAvgspeed(sumSpeed/trackingCount);
			archiver.setArchivetime(new Date());
			try {
				archiver.setStarttime(DateUtils.getStandardDateTime(startTime));
				
			} catch (ParseException e) {
				archiver.setStarttime(null);
				e.printStackTrace();
			}
			try {
				archiver.setEndtime(DateUtils.getStandardDateTime(endTime));
			} catch (ParseException e) {
				archiver.setEndtime(null);
				e.printStackTrace();
			}
			int res = vehicleHourlyArchiveService.insert(archiver);
            logger.info("schedule ing :vehicleId:" + vehicleId + "|tracking size:" + trackingList.size() + "|maxSpeed:"+maxSpeed+"|avgSpeed:"+sumSpeed/trackingCount
					+"|sumDistance:"+sumDistance);
			
		}
		logger.info("schedule end...");

	}

}
